import {
  Controller,
  Get,
  Post,
  Delete,
  Param,
  Query,
  UseGuards,
  Req,
  Body,
  BadRequestException,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { ShareService } from './share.service';
import { CreateLinkShareDto } from './dto/link-share.dto';

@Controller('shares')
@UseGuards(JwtAuthGuard)
export class ShareController {
  constructor(private shareService: ShareService) {}

  @Post()
  @HttpCode(HttpStatus.OK)
  async createShare(
    @Req() req,
    @Body() body: { novelId: number; shareMessage?: string },
  ) {
    const userId = req.user['userId'];
    if (!body.novelId) {
      throw new BadRequestException('小说ID不能为空');
    }

    const share = await this.shareService.createShare(
      userId,
      body.novelId,
      body.shareMessage,
    );

    return {
      success: true,
      message: '分享成功',
      share,
    };
  }

  @Get('my')
  async getMyShares(
    @Req() req,
    @Query('page') page = 1,
    @Query('limit') limit = 10,
  ) {
    const userId = req.user['userId'];
    return this.shareService.getUserShares(userId, Number(page), Number(limit));
  }

  @Get('public')
  async getPublicShares(@Query('page') page = 1, @Query('limit') limit = 10) {
    return this.shareService.getPublicShares(Number(page), Number(limit));
  }

  @Get('novel/:novelId')
  async getNovelShares(
    @Param('novelId') novelId: number,
    @Query('page') page = 1,
    @Query('limit') limit = 10,
  ) {
    return this.shareService.getNovelShares(
      Number(novelId),
      Number(page),
      Number(limit),
    );
  }

  @Post(':id/view')
  @HttpCode(HttpStatus.OK)
  async incrementViewCount(@Param('id') id: number) {
    await this.shareService.updateShareViewCount(Number(id));
    return {
      success: true,
      message: '浏览次数更新成功',
    };
  }

  @Delete(':id')
  async deleteShare(@Req() req, @Param('id') id: number) {
    const userId = req.user['userId'];
    await this.shareService.deleteShare(userId, Number(id));
    return {
      success: true,
      message: '删除分享成功',
    };
  }

  @Post('link')
  @HttpCode(HttpStatus.OK)
  async createShareFromLink(
    @Req() req,
    @Body() createLinkShareDto: CreateLinkShareDto,
  ) {
    // const userId = req.user['userId'];

    try {
      const result = await this.shareService.createShareFromLink(
        1,
        createLinkShareDto.shareUrl,
        createLinkShareDto.shareMessage,
      );

      return {
        success: true,
        message: '链接分享创建成功',
        data: result,
      };
    } catch (error) {
      throw new BadRequestException(error.message);
    }
  }
}
